(async function () {
  const close = $(".close");
  const nickname = $("#nickname");
  const loginId = $("#loginId");
  const chatContainer = $(".chat-container");
  // 判断用户是否登录
  const resp = await API.profile();
  const user = resp.data;
  const msg = $('#txtMsg');
  const msgContainer = $('.msg-container');
  // 如果user为空 说明没有返回用户数据 即没有登录
  if (!user) {
    alert("login please");
    location.href = "./login.html";
    return;
  }

  nickname.innerText = user.nickname;
  loginId.innerText = user.loginId;

  // 退出登录
  close.onclick = function () {
    API.loginOut();
    location.href = "./login.html";
  };
  // 聊天内容相关

  // 添加聊天dom到html中  参数是一个对象 服务给的对象
  function addChat(data) {
    const div = $$$("div");
    div.classList.add("chat-item");
    // 判断消息的发送者
    if (data.from) {
      div.classList.add("me");
    }
    const img = $$$("img");
    img.classList.add("chat-avatar");
    img.src = data.from ? "./asset/avatar.png" : "./asset/robot-avatar.jpg";
    const content = $$$("div");
    content.classList.add("chat-content");
    content.innerText = data.content;
    const time = $$$("div");
    time.classList.add("chat-date");
    time.innerText = formatTime(data.createdAt);

    div.appendChild(img);
    div.appendChild(content);
    div.appendChild(time);

    chatContainer.appendChild(div);
  }

  // 格式化时间戳
  function formatTime(time) {
    const date = new Date(time);
    const year = date.getFullYear();
    // 月份需要补零
    const mouth = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDay().toString().padStart(2, "0");
    const hour = date.getHours().toString().padStart(2, "0");
    const minute = date.getMinutes().toString().padStart(2, "0");
    const second = date.getSeconds().toString().padStart(2, "0");
    return `${year}-${mouth}-${day} ${hour}:${minute}:${second}`;
  }
  addChat({
    _id: "627cd13863832f0548a21ce8",
    from: "haha",
    to: null,
    content: "my name is芝芝",
    createdAt: 1652347192389,
  });
  // 加载历史消息
//   await loadHistory();
  async function loadHistory() {
    const resp = await API.getHistory();
    for (const item of resp.data) {
         addChat(item);
    }
    scrollBottom();
  }
 

  // 设置滚动条在最下方
  function scrollBottom(){
  chatContainer.scrollTop = chatContainer.scrollHeight;

  }
//   发送消息
    async function sendMessage () {
    const value = msg.value;
    
    // 用户发的消息要直接显示到聊天框
    const chatObj = {
        from:user.loginId,
        to : null,
        content : value,
        createdAt: Date.now()
    }
    addChat(chatObj);
    msg.value = '';
    scrollBottom();

   const resp = await API. sendChat(value);
   addChat({
    from:null,
    to:user.loginId,
    ...resp.data});
    scrollBottom();


}
  
msgContainer.onsubmit = function(e){
    e.preventDefault();
    sendMessage ()
}


})();
